import { Context } from 'koa';
import { ResponseCode, ResponseCodeMsg } from '../config/responseCode';
import { utils } from './utils';

export interface ApiResponse<T = any> {
  code: ResponseCode;
  msg: string;
  data: T;
  requestId: string;
}

/**
 * 统一响应格式
 */
export function success<T>(ctx: Context, data?: T, code: ResponseCode = ResponseCode.SUCCESS): void {
  const requestId = ctx.state.requestId || utils.generateUUID();
  const response: ApiResponse<T> = {
    code,
    msg: ResponseCodeMsg[code],
    data: data || ({} as T),
    requestId,
  };
  ctx.body = response;
}

export function error(ctx: Context, code: ResponseCode, msg?: string): void {
  const requestId = ctx.state.requestId || utils.generateUUID();
  const response: ApiResponse = {
    code,
    msg: msg || ResponseCodeMsg[code],
    data: {},
    requestId,
  };
  ctx.body = response;
  ctx.status = code >= 500 ? 500 : code >= 400 ? 400 : 200;
}

